<?php

namespace App\Tables;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Region extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    /**
     * 级联获取下级市区
     * @return array
     */
    public function formatTree()
    {
        $regions = $this->withTrashed()->get(['name', 'code', 'short_name', 'pcode']);

        if ($regions->isEmpty()) {
            return [];
        }

        $regions = $regions->toArray();
        $func = function ($code) use (&$func, &$regions) {
            $tree = array();

            foreach ($regions as $key => $item) {
                if ($item['pcode'] == $code) {
                    $item['disabled'] = empty($item['deleted_at']) ? false : true;

                    $children = $func($item['code']);
                    if (!empty($children)) {
                        $item['children'] = $children;
                    }

                    $tree[] = $item;
                    unset($regions[$key]);
                }
            }

            return $tree;
        };

        return $func(100000);
    }
}
